package com.ruoyi.help.utils;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class MarketPasswordUtil {

    private static final String IV = "1234567890123456";
    private static final String AES_KEY = "1234567890654321";
    public static final String AES_TYPE = "AES/CBC/PKCS5Padding";

    public static String encode(String password) {
        try {
            IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
            //两个参数，第一个为私钥字节数组， 第二个为加密方式 AES或者DES
            SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] encryptedData = cipher.doFinal(password.getBytes());
            return Hex.encodeHexString(encryptedData);
        } catch (Exception e) {
            return null;
        }
    }

    public static String decode(String encodePassword) {
        try {
            byte[] decodeByte = Hex.decodeHex(encodePassword.toCharArray());
            IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
            SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            //解密模式
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] bytes = cipher.doFinal(decodeByte);
            return new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}